package com.lbd.commons.listener;

import com.alibaba.fastjson.JSON;
import com.lbd.commons.EventName;
import com.lbd.commons.event.AbstractEvent;
import com.lbd.system.bean.EventLog;
import com.lbd.system.service.EventLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by WangYajie on 2016/8/29.
 */
public abstract class AbstractListener<T extends AbstractEvent<E>, E> implements ApplicationListener<T> {
    private static final Logger log = LoggerFactory.getLogger(AbstractListener.class);
    @Autowired
    EventLogService eventLogService;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void onApplicationEvent(T event) {
        String eventName = event.getClass().getSimpleName();
        String result = "";
        try {
            log.info(JSON.toJSONString(event));
            if (event.getClass().isAnnotationPresent(EventName.class)) {
                eventName = event.getClass().getAnnotation(EventName.class).value();
            }
            switch (event.eventState) {
                case SUCCESS:
                    onSuccess(event.getEntity(), event.getMessage());
                    break;
                case FAIL:
                    onFail(event.getEntity(), event.getMessage());
                    break;
                case ERROR:
                    onError(event.getEntity(), event.getMessage());
                    break;
            }
            result = "执行成功";
        } catch (Exception e) {
            log.info("事件异常了", e);
            result = "执行失败" + e.getMessage();
        } finally {
            eventLogService.save(new EventLog(eventName, JSON.toJSONString(event), result, this.getClass().getName(), event.hashCode() + ""));
        }
    }

    /**
     * 事件成功
     *
     * @param entity  事件信息
     * @param message 事件消息,可能为null
     */

    public abstract void onError(E entity, String message);

    /**
     * 事件失败
     *
     * @param entity  事件信息
     * @param message 事件消息,可能为null
     */
    public abstract void onFail(E entity, String message);

    /**
     * 事件异常
     *
     * @param entity  事件信息
     * @param message 事件消息,可能为null
     */
    public abstract void onSuccess(E entity, String message);


}
